package com.example.test04;

import android.app.Activity;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    Button bind, unbind, getServiceStatus;
    BindService.MyBinder binder;

    private ServiceConnection conn = new ServiceConnection()
    {
        // 当该Activity与Service连接成功时回调该方法
        @Override
        public void onServiceConnected(ComponentName name
                , IBinder service)
        {
            System.out.println("--Service Connected--");
            // 获取Service的onBind方法所返回的MyBinder对象
            binder = (BindService.MyBinder) service; //①
        }

        // 当该Activity与Service断开连接时回调该方法
        @Override
        public void onServiceDisconnected(ComponentName name)
        {
            System.out.println("--Service Disconnected--");
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 获取程序界面中的bind、unbind、getServiceStatus按钮
        bind = findViewById(R.id.bind);
        unbind = findViewById(R.id.unbind);
        getServiceStatus = findViewById(R.id.getServiceStatus);

        bind.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View source)
            {
                // 绑定指定Service
                Intent intent = new Intent(MainActivity.this,BindService.class);
                bindService(intent, conn, Service.BIND_AUTO_CREATE);

            }
        });
        unbind.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View source)
            {
                // 解除绑定Service
                unbindService(conn);
            }
        });
        getServiceStatus.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View source)
            {
                // 获取、并显示Service的count值
                Intent intent = new Intent(MainActivity.this,BindService.class);
                startService(intent);
                Toast.makeText(MainActivity.this,
                        "Service的count值为：" + binder.getCount(),
                        Toast.LENGTH_SHORT).show(); //②
            }
        });
    }
}
